Windows Networking API Reference

MSDN Community | Topic: Winsock

Winsock API Reference

The Windows Sockets API (Winsock) is a Microsoft-specific implementation of the Berkeley sockets API. It provides a standard interface for Windows applications to access network services. Winsock supports both connection-oriented and connectionless network communication using a variety of protocols, including TCP/IP.

Key Concepts

  • Sockets: An endpoint for communication.
  • Protocols: Such as TCP (Transmission Control Protocol) and UDP (User Datagram Protocol).
  • Address Families: AF_INET for IPv4, AF_INET6 for IPv6.
  • Service Providers: Implementations of network protocols.

Core Functions

The Winsock API provides a rich set of functions for network programming. Here are some of the most commonly used:

Socket Creation and Management

socket(): Creates a socket.

bind(): Associates a local address with a socket.

listen(): Places a socket in a state for listening for incoming connections.

accept(): Accepts a connection on a socket.

connect(): Establishes a connection to a remote host.

closesocket(): Closes a socket.

Data Transmission

send() / sendto(): Sends data over a socket.

recv() / recvfrom(): Receives data from a socket.

sendmsg() / recvmsg(): More advanced data sending and receiving.

Address Information

gethostname(): Retrieves the standard host name for the current computer.

gethostbyname(): Retrieves host information from a name server.

getaddrinfo(): Retrieves address structures for a specified host and service.

freeaddrinfo(): Frees address structures allocated by getaddrinfo().

Error Handling

WSAGetLastError(): Retrieves the error code for the last Winsock operation.

WSAStartup(): Initializes the Winsock DLL.

WSACleanup(): Terminates the use of the Winsock DLL.

Example Snippet (Conceptual)

Here's a simplified look at creating a TCP server socket:


#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")

// ... initialization code ...

SOCKET serverSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (serverSocket == INVALID_SOCKET) {
    // Handle error
    return 1;
}

struct sockaddr_in serverAddr;
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(8080); // Example port
serverAddr.sin_addr.s_addr = INADDR_ANY;

if (bind(serverSocket, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR) {
    // Handle error
    closesocket(serverSocket);
    return 1;
}

if (listen(serverSocket, SOMAXCONN) == SOCKET_ERROR) {
    // Handle error
    closesocket(serverSocket);
    return 1;
}

// ... accept connections and handle data ...

closesocket(serverSocket);
// ... cleanup code ...
                

For detailed function signatures, parameter descriptions, return values, and code examples, please refer to the official Microsoft Developer Network (MSDN) documentation.